<?php

/**
 * This is the model class for table "tbl_employees".
 *
 * The followings are the available columns in table 'tbl_employees':
 * @property string $empno
 * @property string $unassign
 * @property string $socsecnum
 * @property string $license
 * @property double $hrrate
 * @property double $overhead
 * @property integer $percent
 * @property string $crew
 * @property string $suffix
 * @property string $firstname
 * @property string $middlename
 * @property string $lastname
 * @property string $add1
 * @property string $add2
 * @property string $city
 * @property string $state
 * @property string $zip
 * @property string $county
 * @property string $country
 * @property string $timezone
 * @property string $pcellphone
 * @property string $phomephone
 * @property string $pemail
 * @property integer $maritalstatus
 * @property integer $gender
 * @property integer $ethnicgroup
 * @property string $title
 * @property string $birthdate
 * @property string $employdate
 * @property string $terminationdate
 * @property string $terminationreason
 * @property string $vacationallowed
 * @property string $photopath
 * @property string $shift
 * @property string $workcell
 * @property string $workext
 * @property string $branch
 * @property string $dept
 * @property string $workemail
 * @property integer $status
 * @property integer $routefrom
 * @property string $MonStart
 * @property string $MonEnd
 * @property string $TueStart
 * @property string $TueEnd
 * @property string $WedStart
 * @property string $WedEnd
 * @property string $ThuStart
 * @property string $ThuEnd
 * @property string $FriStart
 * @property string $FriEnd
 * @property string $SatStart
 * @property string $SatEnd
 * @property string $SunStart
 * @property string $SunEnd
 * @property string $image
 * @property int $sickallowed
 */
class Employees extends CanLockRecord {

    public $file;

    /**
     * Returns the static model of the specified AR class.
     * @return Employees the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'tbl_employees';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('empno, firstname, lastname, status', 'required'),
            array('percent, maritalstatus, gender, ethnicgroup, status, routefrom', 'numerical', 'integerOnly' => true),
            array('hrrate, overhead', 'numerical'),
            array('empno', 'length', 'max' => 4),
            array('unassign', 'length', 'max' => 1),
            array('socsecnum', 'length', 'max' => 9999),
            array('license, shift', 'length', 'max' => 20),
            array('crew', 'length', 'max' => 15),
            array('suffix', 'length', 'max' => 5),
            array('firstname, middlename, lastname, title, branch', 'length', 'max' => 75),
            array('add1, add2, city, county, country, timezone, dept', 'length', 'max' => 50),
            array('state', 'length', 'max' => 2),
            array('zip, vacationallowed,sickallowed', 'length', 'max' => 10),
            array('pcellphone, phomephone, workcell', 'length', 'max' => 12),
            array('pemail, photopath, workemail', 'length', 'max' => 255),
            array('workext', 'length', 'max' => 6),
            array('status', 'checkTermination'),
            array('MonStart, MonEnd, TueStart, TueEnd, WedStart, WedEnd, ThuStart, ThuEnd, FriStart, FriEnd, SatStart, SatEnd, SunStart, SunEnd', 'length', 'max' => 8),
            array('MonStart, MonEnd, TueStart, TueEnd, WedStart, WedEnd, ThuStart, ThuEnd, FriStart, FriEnd, SatStart, SatEnd, SunStart, SunEnd', 'checkTime', 'allowEmpty' => true),
            array('file', 'file', 'types' => 'jpg,png,jpeg,bmp,gif', 'maxSize' => 1000000, 'allowEmpty' => true),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('empno, unassign, socsecnum, license, hrrate, overhead, percent, crew, suffix, firstname, middlename, lastname, add1, add2, city, state, zip, county, country, timezone, pcellphone, phomephone, pemail, maritalstatus, gender, ethnicgroup, title, birthdate, employdate, terminationdate, terminationreason, vacationallowed, photopath, shift, workcell, workext, branch, dept, workemail, status, routefrom, MonStart, MonEnd, TueStart, TueEnd, WedStart, WedEnd, ThuStart, ThuEnd, FriStart, FriEnd, SatStart, SatEnd, SunStart, SunEnd', 'safe', 'on' => 'search'),
        );
    }

    public function checkTermination($attribute, $params) {
        if ($this->status == 0 && ($this->terminationdate == NULL || $this->terminationreason == NULL)) {
            $this->addError('status', 'Termination date and termination reason need to be filled');
        }
    }

    public function checkTime($attribute, $params) {
        $error = false;
        if ($this->$attribute != NULL) {
            $match = preg_match('/^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/', $this->$attribute);
            if ($match == 0) {
                $error = true;
            }
        } else if ($params['allowEmpty'] == false) {
            $error = true;
        }
        if ($error)
            $this->addError($attribute, 'The time is not correct');
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'empno' => 'Empno',
            'unassign' => 'Unassign',
            'socsecnum' => 'SS Number',
            'license' => 'License',
            'hrrate' => 'Hourly rate',
            'overhead' => 'Over Head',
            'percent' => 'Percent',
            'crew' => 'Crew',
            'suffix' => 'Suffix',
            'firstname' => 'First Name',
            'middlename' => 'Middle Name',
            'lastname' => 'Last Name',
            'add1' => 'Address 1',
            'add2' => 'Address 2',
            'city' => 'City',
            'state' => 'State',
            'zip' => 'Zip',
            'county' => 'County',
            'country' => 'Country',
            'timezone' => 'Timezone',
            'pcellphone' => 'Personal Cell Phone',
            'phomephone' => 'Home Phone',
            'pemail' => 'Personal E-mail',
            'maritalstatus' => 'Marital Status',
            'gender' => 'Gender',
            'ethnicgroup' => 'Ethnic Group',
            'title' => 'Title',
            'birthdate' => 'Birthdate',
            'employdate' => 'Hired Date',
            'terminationdate' => 'Termination Date',
            'terminationreason' => 'Termination Reason',
            'vacationallowed' => 'Allowed Vacation (Hours/Year)',
            'sickallowed' => 'Allowed Sick (Hours/Year)',
            'photopath' => 'Photopath',
            'shift' => 'Shift',
            'workcell' => 'Work Cell',
            'workext' => 'Work Exention',
            'branch' => 'Branch',
            'dept' => 'Department',
            'workemail' => 'Work E-mail',
            'status' => 'Status',
            'routefrom' => 'Route From',
            'MonStart' => 'Mon Start',
            'MonEnd' => 'Mon End',
            'TueStart' => 'Tue Start',
            'TueEnd' => 'Tue End',
            'WedStart' => 'Wed Start',
            'WedEnd' => 'Wed End',
            'ThuStart' => 'Thu Start',
            'ThuEnd' => 'Thu End',
            'FriStart' => 'Fri Start',
            'FriEnd' => 'Fri End',
            'SatStart' => 'Sat Start',
            'SatEnd' => 'Sat End',
            'SunStart' => 'Sun Start',
            'SunEnd' => 'Sun End',
        );
    }

    public function getGenderList() {
        return array(
            '0' => 'Male',
            '1' => 'Female'
        );
    }

    public function getGenderText() {
        return isset($this->genderList[$this->gender]) ? $this->genderList[$this->gender] : NULL;
    }

    public function beforeSave() {
        $crypt=new cryptastic();
     
     
        $oldModel = Employees::model()->findByPk($this->empno);
        if ($oldModel == NULL) {
            $this->socsecnum = $crypt->encrypt($this->socsecnum,Yii::app()->params['encryptKey']);
        } else {
       
            if ($this->socsecnum != '') {
                $this->socsecnum = $crypt->encrypt($this->socsecnum,Yii::app()->params['encryptKey']);
                
            } else {
                $socsec=Yii::app()->db->createCommand('select socsecnum from tbl_employees where empno=:empno')->bindValue('empno',$this->empno)->queryScalar();
                $this->socsecnum=$socsec;                                           
            }
        }
        $this->file = CUploadedFile::getInstance($this, 'file');


        if ($this->file != NULL) {
            //made a random name base on timestamp
            $ext = getFileExt($this->file);
            $name = getFileBodyName($this->file);


            $this->image = 'emp-' . $this->empno . '-' . $name . '_' . date('Y-d-m') . $ext;
            getImageBySize($this->image, 150, 150);

            $this->file->saveAs('images/content/' . $this->image, true);
        }
        return parent::beforeSave();
    }

    public function getEthnicityList() {
        return array(
            '0' => 'Indian',
            '1' => 'Asia',
            '2' => 'African American',
            '3' => 'Hispanic',
            '4' => 'White',
            '5' => 'Other',
        );
    }

    public function getEthnicityText() {
        return isset($this->ethnicityList[$this->ethnicgroup]) ? $this->ethnicityList[$this->ethnicgroup] : NULL;
    }

    public function getTimeZoneList() {
        $data = Yii::app()->db->createCommand('select * from tbl_timezone')->queryAll();
        $rs = array();
        if (count($data) > 0) {
            foreach ($data as $item) {
                $rs[$item['id']] = $item['id'];
            }
        }
        return $rs;
    }

    public function getMaritalStatusList() {
        return array(
            1 => 'Married',
            2 => 'Divorce',
            0 => 'Single'
        );
    }

    public function getShiftList() {
        return array(
            '1' => '1st Shift',
            '2' => '2nd Shift',
            '3' => '3rd Shift',
        );
    }

    public function getStatusList() {
        return array(
            1 => 'Active',
            0 => 'Inactive',
        );
    }

    public function getAssignedWareHouse() {
        $data = Yii::app()->db->createCommand('select * from tbl_warehouse where empno=:empno AND status=0')->bindValue('empno', $this->empno)->queryAll();
        $rs = array();
        if (count($data) > 0) {
            foreach ($data as $item) {
                $rs[] = array(
                    'warehouseid' => $item['warehouseid'],
                    'warehousedesc' => $item['warehousedesc']
                );
            }
        }
        return $rs;
    }

    public function getRemainVacationHours() {
        $remain = 0;
        $data = Yii::app()->db->createCommand('select * from tbl_vacationhrs where empno=:empno AND YEAR(NOW())=YEAR(datetaken)')->bindValue('empno', $this->empno)->queryAll();
        if (count($data) > 0) {
            foreach ($data as $item) {
                $remain+=intval($item['hours']);
            }
        }
        return $remain;
    }

    public function getRemainSickHours() {
        $remain = 0;
        $data = Yii::app()->db->createCommand('select * from tbl_sickhrs where empno=:empno AND YEAR(NOW())=YEAR(datetaken)')->bindValue('empno', $this->empno)->queryAll();
        if (count($data) > 0) {
            foreach ($data as $item) {
                $remain+=intval($item['hours']);
            }
        }
        return $remain;
    }

    public function getRouteFromList() {
        return array(
            '0' => 'Company Address',
            '1' => 'Employee Address'
        );
    }

    public function getRouteFromText() {
        return isset($this->routeFromList[$this->routefrom]) ? $this->routeFromList[$this->routefrom] : NULL;
    }

    public function getEmployeeList() {
        $data = Yii::app()->db->createCommand('select firstname,lastname,empno from tbl_employees')->queryAll();
        $rs = array();
        //$rs['']="N/A";
        if (count($data) > 0) {
            foreach ($data as $item) {
                $rs[$item['empno']] = $item['firstname'] . ' ' . $item['lastname'];
            }
        }
        return $rs;
    }

    public function afterFind() {
        parent::afterFind();
        $this->socsecnum = '';
    }

    public function getSalePersonList() {
        $emplist = Yii::app()->db->createCommand('select * from tbl_employees where lower(dept)="sales"')->queryAll();
        $rs = array(
        );
        if (count($emplist) > 0) {
            foreach ($emplist as $emp) {
                $rs[$emp['empno']] = $emp['firstname'] . ' ' . $emp['lastname'];
            }
        }
        return $rs;
    }

}